// UVIEW UI
import Schema from "uview-ui/libs/util/async-validator";
import {isString} from "@/utils/Validate";
import Modal from "@/utils/Modal";

/**
 * @Description:表单校验
 */
class Validator {
  /**
   * @Description:初始化传入校验规则
   * @param {Object} descriptor
   */
  constructor(descriptor) {
    this.descriptor = descriptor;
    this.validator = new Schema(descriptor);
  }

  /**
   * @Description:校验某些字段
   * @param {Array|string} fields 字段名列表
   * @param {Object} source 数据源
   */
  validateField(fields,source) {
    if (isString(fields)) {
      fields = [fields];
    }
    const descriptor = {};
    Object.keys(this.descriptor).forEach(key => {
      if (fields.indexOf(key) !== -1) {
        descriptor[key] = this.descriptor[key];
      }
    })
    return new Validator(descriptor).validate(source)
  }

  /**
   * @Description:校验全部字段
   */
  validate(fields) {
    const promise = new Promise((resolve, reject) => {
      this.validator.validate(fields, (errors, fields) => {
        if (errors) {
          Modal.toast.info(errors[0].message);
          reject(errors);
        } else {
          resolve(fields);
        }
      })
    })
    return promise;
  }
}

export default Validator
